package com.proyecto.dao;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.proyecto.modelo.Usuario;
import com.proyecto.modelo.Vehiculo;

@Repository
public class VehiculoDaoImpl extends SpringHibernateDao<Vehiculo> implements VehiculoDao{
	
	@Autowired
	public VehiculoDaoImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	@Override
	public void eliminar(List<Vehiculo> objetos) throws DataAccessException {
		Session session = getSession();
		Vehiculo vehiculo;
		Iterator<Vehiculo> iterator = objetos.iterator();
		
		while (iterator.hasNext()) {
			vehiculo = (Vehiculo) iterator.next();
			session.delete(vehiculo);
		}
	}

	@Override
	public void eliminar(Vehiculo objeto) throws DataAccessException {
		getSession().delete(objeto);
	}

	@Override
	public void guardar(List<Vehiculo> objetos) throws DataAccessException {
		Session session = getSession();
		Vehiculo vehiculo;
		Iterator<Vehiculo> iterator = objetos.iterator();
		
		while (iterator.hasNext()) {
			vehiculo = (Vehiculo) iterator.next();
			session.save(vehiculo);
		}
	}

	@Override
	public void guardar(Vehiculo objeto) throws DataAccessException {
		getSession().save(objeto);
		
	}

	@Override
	public Vehiculo getVehiculo(Integer patente) {
		Query query = getSession().createQuery("select vehiculo" +
				"from Vehiculo as vehiculo" +
				"where vehiculo.patente = :patente");

		query.setParameter("patente", patente);
		return (Vehiculo)query.uniqueResult();
	}

	@Override
	public Collection<Vehiculo> obtenerVehiculosCon(String marca, String modelo) {
		Query query = getSession().createQuery("from Vehiculo as vehiculo" +
				"where vehiculo.marca = :marca" +
				"and whiculo.modelo = :modelo");
		query.setParameter("marca", marca);
		query.setParameter("modelo", modelo);
		return query.list();
	}

	@Override
	public Collection<Vehiculo> obtenerVehiculosCon(Usuario duenio) {
		Query query = getSession().createQuery("from Vehiculo as vehiculo" +
				"where vehiculo.duenio = :duenio");
		query.setParameter("duenio", duenio);
		return query.list();
	}

	@Override
	protected Class<Vehiculo> getObjetoManejado() {
		return Vehiculo.class;
	}	

}
